﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Helpers;
using System.Collections.Generic;
using Model;
using System.IO;

namespace FEIStorageSite.Admin
{
    public partial class Default : System.Web.UI.Page
    {
        List<CategoryItem> categoriesList;

        protected void Page_Load(object sender, EventArgs e)
        {
            DAL.connectionString = "Data Source=" + Server.MapPath("App_Data\\fei_storage.db");

            if (!IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            categoriesList = DAL.GetCategories();
            categoriesListView.DataSource = categoriesList;
            categoriesListView.DataBind();
        }

        protected void OnItemCommandOccured(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                switch (e.CommandName)                    
                {
                    case "UpdateItem":
                        CategoryItem categoryEdited = new CategoryItem();
                        categoryEdited.ID = Convert.ToInt32(e.CommandArgument);
                        categoryEdited.Name = ((TextBox)e.Item.FindControl("nameTextBox")).Text;
                        DAL.EditCategory(categoryEdited);
                        BindData();
                        break;
                    case "DeleteItem":
                        int IDDelete = Convert.ToInt32(e.CommandArgument);

                        if (DAL.GetCategoryCountFiles(IDDelete) != 0)
                        {
                            throw new Exception("Непуста категорія не може бути видалена");
                        }

                        DAL.DeleteCategory(IDDelete);
                        BindData();
                        break;
                    case "AddItem":
                        string nameAdded = ((TextBox)categoriesListView.FindControl("newNameTextBox")).Text;

                        if (nameAdded == String.Empty)
                        {
                            throw new Exception("Назва нової категорії не може бути пустою");
                        }

                        ((TextBox)categoriesListView.FindControl("newNameTextBox")).Text = string.Empty;
                        DAL.CreateCategory(nameAdded);
                        BindData();
                        break;
                }
            }
            catch (Exception exception)
            {
                categoriesPageError.Text = exception.Message;
            }
        }      
    }
}
